import { AnimatedSprite } from 'pixi.js'
import { imageToTexture, loadBase64 } from "../../util.js";
export function Portal(resource, stage) {
    this.resource = resource;
    this.portalTextureArr = {
        pv: []
    }
    this.stage = stage;
    this.stageStack = [];
}

Portal.prototype.init = async function init() {
    let portalInfo = this.resource.Content.Map['MapHelper.img'].portal.game;
    for (let item of Object.values(portalInfo.pv)) {
        const { value, origin } = item;
        const image = await loadBase64(value)
        const texture = await imageToTexture(image);
        texture.defaultAnchor.x = origin.x / image.width;
        texture.defaultAnchor.y = origin.y / image.height;
        this.portalTextureArr.pv.push(texture);
    }


    
}

/**
 * 
 * @private
 * @param {string} type 
 * @returns {AnimationSprite}
 */
Portal.prototype.clip = function(type) {
    const pvArr = this.portalTextureArr[type];
    const animationSprite = new AnimatedSprite(pvArr);
    animationSprite.updateAnchor = true;
    animationSprite.animationSpeed = 0.1;
    return animationSprite;
}

Portal.prototype.draw = function(MapPortalInfo) {
    Object.values(MapPortalInfo).forEach(portal => {
        const x = Number(portal.x);
        const y = Number(portal.y);
        // tm 去哪， tn 从哪里来
        const { tm, tn } = portal; 
        if ((tn.length !== 0 && tn !== '999999999') || (tm.length !== 0 && tm !== '999999999')) {
            const ani = this.clip('pv');
            window.portal = ani;
            ani.x = x;
            ani.y = y;
            ani.zIndex = 100000;
            this.stage.addChild(ani);
            this.stageStack.push(ani);
            ani.play();
        }
    })
}

Portal.prototype.removeAll = function() {
    this.stageStack.forEach(ani => {
        ani.stop();
        this.stage.removeChild(ani);
    })
    this.stageStack.length = 0;
}